'use strict';

const createConfig = require('uni-config-center');
const uidConfig = createConfig({
	pluginId: 'uni-id'
});

const uidPay = require('uni-pay');
const db = uniCloud.database();

exports.main = async (event, context) => {
	let response = {
		mpserverlessComposedResponse: true,
		statusCode: 200,
		headers: {
			'content-type': 'text/xml;charset=utf-8'
		},
		body: `<xml><return_code><![CDATA[FAILD]]></return_code><return_msg><![CDATA[异常回调]]></return_msg></xml>`
	};

	const path = event.path;
	let res = {};
	
	let notifyType = 'payment';
	let payObj = {
		name: '微信支付',
		way: 'wxpay'
	};
	switch (path) {
		case '/':
		case '/wxpay':
		case '/wxpay-app':
		case '/wxpay-h5wx':
			let wxpayConfig;
			if (path == '/wxpay-app') {
				wxpayConfig = uidConfig.config('app.wxpay');
			} else if (path == '/wxpay-h5wx') {
				wxpayConfig = uidConfig.config('h5-weixin.pay');
			} else {
				wxpayConfig = uidConfig.config('mp-weixin.pay');
			}
			const uniWxpayIns = uidPay.initWeixin(wxpayConfig);
			res = await uniWxpayIns.verifyPaymentNotify(event);
		
			break;
		case '/alipay':
		case '/alipay-app':
			let alipayConfig = uidConfig.config('mp-alipay.pay');
			if (path == '/alipay-app') {
				alipayConfig = uidConfig.config('app.alipay');
			}
			const uniAlipayIns = uidPay.initAlipay(alipayConfig);
			notifyType = await uniAlipayIns.checkNotifyType(event)
			if (notifyType === 'refund') {
				// 退款通知
			} else if (notifyType === 'payment') {
				// 支付结果通知
			}
			uniCloud.logger.info(notifyType);
			
			res = await uniAlipayIns.verifyPaymentNotify(event);

			payObj.name = '支付宝支付';
			payObj.way = 'alipay';
			break;
		default:
			break;
	}
	
	if (res && (res.returnCode == 'SUCCESS' || res.resultCode == 'SUCCESS') && notifyType == 'payment') {
		const {
			outTradeNo,
			totalFee,
			transactionId,
			openid
		} = res;
		
		let payRes = await db.collection('usemall-order-pay')
			.where({
				order_id: outTradeNo
			})
			.get();

		if (!(payRes && payRes.data && payRes.data.length == 1)) {
			uniCloud.logger.info(`支付号[${outTradeNo}]不存在`);
			return response;
		}
		
		const pay = payRes.data[0];
		const uid = pay.create_uid;

		// todo 开启事务
		const nowdate = new Date().getTime();
		
		let nowtime = toDateUTC8(new Date());
		let plus_time = new Date();
		// 1年会员有效期
		plus_time.setFullYear(plus_time.getFullYear() + 1);
		
		// 写入付费会员数据
		await db.collection('usemall-member-paying').add({
			member_uid: uid,
			pay_id: outTradeNo,
			pay_title: 'VIP会员费',
			pay_money: totalFee,
			pay_openid: openid,
			pay_way: payObj.way,
			pay_original: payObj.name,
			pay_preid: pay.pay_preid,
			pay_notify: event,
			pay_time: nowdate,
			pay_no: transactionId,
			pay_yy_mm: nowtime.getFullYear() + '-' + (nowtime.getMonth() + 1),
			pay_yy_mm_dd: nowtime.getFullYear() + '-' + (nowtime.getMonth() + 1) + '-' + nowtime.getDate(),
			pay_time: nowdate,
			wx_delivery: pay.wx_delivery,
			wx_delivery_sync: pay.wx_delivery_sync,
			expire_time: plus_time.getTime(),
			pay_state: '已付款',
			version: 1,
			create_time: nowdate,
			create_uid: uid
		});

		// 修改订单支付数据
		await db.collection('usemall-order-pay').where({
			order_id: outTradeNo
		}).update({
			version: db.command.inc(1),
			pay_state: '已付款',
			pay_notify: event,
			pay_time: nowdate,
			pay_no: transactionId,
			pay_openid: openid
		});

		// todo 已付费会员，再次支付
		// 	1. 会员如果有效，当前的过期时间 = 上一次过期时间 +1年
		// 	2. 会员如果无效，当前的过期时间 = 现在的时间 +1年
		
		// 修改付费会员数据
		const memberRes = await db.collection('usemall-member').doc(uid).update({
			member_monetary: db.command.inc(totalFee),
			is_plus: '付费会员',
			plus_time: plus_time.getTime()
		});

		if (payObj.way == 'wxpay') {
			response.body =
				`<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>`;
		} else if (payObj.way == 'alipay') {
			response.headers['content-type'] = 'text/plain';
			response.body = 'success';
		}
	}
	
	if (notifyType == 'refund') {
		if (payObj.way = 'alipay') {
			response.headers['content-type'] = 'text/plain';
			response.body = 'success';
		}
	}

	uniCloud.logger.info(res);
	uniCloud.logger.info(response);

	return response;
};


/**
 * 将 UTC+0 转换为 UTC+8
 */
function toDateUTC8(date) {
	if (uniCloud.$provider == 'alipay') {
		// 支付宝云，默认为 UTC+8
		return date;
	}
	
	// 小时 UTC+0 转换为 UTC+8
	date.setHours(date.getHours() + 8);
	return date;
}
